<template>
  <el-dialog
    :title="'解答学生提问'"
    :visible.sync="dialogVisible"
    width="30%" style="min-width: 400px;" @open="onDialogOpen">
    <div v-if="questions.length > 0">
      <div style="width: 100%; text-align: left;">
        提问学生：{{ questions[currentPage].student }}
      </div>
      <el-input type="textarea" :rows="4" :value="questions[currentPage].content" readonly></el-input>
      <div style="width: 100%; margin-top: 10px; text-align: left;">
        回答：
      </div>
      <el-input
        type="textarea"
        :rows="4"
        v-model="questions[currentPage].answer">
      </el-input>
      <div style="margin-top: 10px; text-align: center;">
        <el-button @click.native="dialogVisible = false" @click="emits('answerQuestion-canceled')">取消</el-button>
        <el-button type="primary" @click.native="submitAnswer()">提交</el-button>
      </div>
    </div>
    <div v-else>
      <el-text class="mx-1">没有问题需要解答</el-text>
    </div>
    <div slot="footer" class="dialog-footer" style="display: flex; flex-direction: column; justify-content: center; align-items: center; margin-top: 20px;">
      <el-pagination
          @current-change="page=>{currentPage=page-1}"
          background
          layout="prev, pager, next"
          :page-count="total"
          class="mt-4"
        />
    </div>
  </el-dialog>
</template>
<script setup>
import { ref } from 'vue';
import { loadQuestionsToAnswer, answerQuestion } from '../utils/apiQuestion.js'
import { myUserInfo } from '../utils/apiUser.js'
import { ElMessage } from 'element-plus';

const dialogVisible = ref(true);
const questions = ref([])
const currentPage = ref(0);
const total = ref(0);

function submitAnswer() {
  answerQuestion(questions.value[currentPage.value].id, questions.value[currentPage.value].answer).then(res=>{
    loadQuestions()
    ElMessage.success('解答成功！')
  })
}

const loadQuestions = () => {
  loadQuestionsToAnswer(myUserInfo().id).then(res=>{
    questions.value = res.data
    total.value = res.data.length
    if (total.value <= currentPage.value) {
      currentPage.value = 0
    }
  })
}

const onDialogOpen = () => {
  loadQuestions()
}

const emits = defineEmits(['answerQuestion-canceled'])

</script>